from fastapi import APIRouter, Depends, status
from fastapi.security import OAuth2PasswordBearer
from sqlalchemy.ext.asyncio import AsyncSession

from scaner.api_v1.auth import utils as auth_utils
from scaner.core.models.user import User
from scaner.core.models import db_helper
from . import schemas
from . import crud
from .dependencies import (
    validate_auth_user,
    get_current_token_payload,
    get_current_active_auth_user,
)


router = APIRouter(tags=["JWT"])

oauth2_schema = OAuth2PasswordBearer(tokenUrl="/api/v1/auth/login/")


@router.post(
    "/signup/",
    response_model=schemas.UserResponse,
    status_code=status.HTTP_201_CREATED,
)
async def register_user(
    user_data: schemas.UserCreate,
    session: AsyncSession = Depends(db_helper.get_async_session),
):
    return await crud.sign_up_user(
        session=session,
        user_data=user_data,
    )


@router.post("/login/", response_model=schemas.TokenInfo)
def auth_user_jwt(user: User = Depends(validate_auth_user)):
    jwt_payload = {
        "sub": user.id,
        "username": user.username,
        "email": user.email,
        "phone": user.phone,
    }

    token = auth_utils.encode_jwt(jwt_payload)

    return schemas.TokenInfo(
        access_token=token,
        token_type="Bearer",
        username=user.username,
    )


@router.get("/me/")
def auth_user_check_info(
    payload: dict = Depends(get_current_token_payload),
    user: User = Depends(get_current_active_auth_user),
):
    iat = payload.get("iat")
    return {
        "username": user.username,
        "email": user.email,
        "logged_in_at": iat,
    }
